#!/usr/bin/env python3

import sys
import argparse 

def bin2hex(src_file, dst_file, byte_num, data_mat):
    stc_fd = open(src_file, "rb")
    dst_fd = open(dst_file, "w")
    if(data_mat == "hex"):
        target_mat = "{:02x}"
        data_len = 2
    elif(data_mat == "bin"):
        target_mat = "{:08b}"
        data_len = 8
    else:
        raise Exception("Unsupported data format: ", data_mat)
    data = stc_fd.read(byte_num)
    byte_cnt = 0 
    while len(data):
        data_hex = ""
        for c in data:
            data_hex = target_mat.format(c) + data_hex
        data_hex = data_hex.rjust(byte_num*data_len, "0")
        print("%08x:"%byte_cnt, data_hex)
        dst_fd.write(data_hex+"\n")
        byte_cnt = byte_cnt + byte_num
        data = stc_fd.read(byte_num)
    stc_fd.close()
    dst_fd.close()
    print("convert %s successful, convert size: %0d bytes (0x%0x)"%(src_file, byte_cnt, byte_cnt))
    print("dst file %s : data format is %s, %0d bytes in one line"%(dst_file, data_mat, byte_num))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='convert file format of bin into file format of hex')
    parser.add_argument(dest='src_file', metavar='"source filename"', nargs=1, default="rom.bin")
    parser.add_argument(dest='dst_file', metavar='"target filename"', nargs=1, default="rom.hex")
    parser.add_argument('-n', '--byte_num', dest="byte_num", metavar='byte_num', type=int, default=4, 
                        help='Specifies the number of bytes per line in  target file')
    parser.add_argument('-f', '--data_format', dest='data_mat', metavar='data_format', choices={'hex','bin'}, default='hex',
                        help='Specifies the data format of the target file')
    args = parser.parse_args()
    bin2hex(args.src_file[0], args.dst_file[0], args.byte_num, args.data_mat)

